package com.sz.biz.common.customer.service.impl;

import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.entity.CusCompany;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.base.service.AreaService;
import com.sz.biz.common.base.dto.AreaDto;
import com.sz.biz.common.customer.service.CustomerCompanyService;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.biz.common.customer.dto.CusCompanyDto;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.service.SysFileGroupService;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xutao on 17/4/1.
 */
@Service("CustomerCompanyInfoService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CustomerCompanyServiceImpl extends AbstractService implements CustomerCompanyService {

    @Autowired
    SysFileGroupService fileGroupService;

    @Autowired
    AreaService areaService;

    @Autowired
    CustomerService customerService;

    @Autowired
    CustomerUserService customerUserService;

    @Autowired
    UserService userService;

    @Override
    public int save(CusCompanyDto entry) {
        checkDataValid(entry);
        checkCompanyExist(entry);
        if (PrincipalUtils.getDomainId() == AppDomain.OPERATION) {
            UserDto userDto = userService.findUserDetailByUserId(PrincipalUtils.getAccountId());
            if (userDto != null) {
                entry.setCreator(userDto.getFullName() + " " + userDto.getUserName());
            }
            else {
                entry.setCreator(PrincipalUtils.getAccountName());
            }
            entry.setCreatorId(PrincipalUtils.getAccountId());
        }
        List<String> attachments = entry.getAttachFileIds();
        if (!CollectionUtils.isEmpty(attachments)) {
            String fileGroupId = fileGroupService.createFileGroup(attachments,
                    "biz.customer.model", "客户" + entry.getRefCustomerId() + "客户公司证件", AppDomain.OPERATION);
            entry.setLicense(fileGroupId);
        }
        dao.save(getSqlName("insertSelective"), entry);
        CusCustomer cusCustomer = customerService.findCustomerById(entry.getRefCustomerId());
        if (checkCustomerInfoAndSetAuthStatus(cusCustomer)) {
            if (cusCustomer.getAuthStatus() == null || cusCustomer.getAuthStatus() < 1) {
                customerService.setCustomerAuthStatus(entry.getRefCustomerId(), 1);
                customerService.createPayAccount(cusCustomer,entry);
            }
        }
        else {
            if (cusCustomer.getAuthStatus() == null || cusCustomer.getAuthStatus() != 0) {
                customerService.setCustomerAuthStatus(entry.getRefCustomerId(), 0);
            }
        }

        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_CUSTOMER_COMPANY", entry);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.ADD, "新增客户公司信息", dataBackup);


        return entry.getId();
    }

    @Override
    public CusCompanyDto findCompanyByCustomerId(Integer refCustomerId) {

        CusCompany cusCompany = (CusCompany) dao.findForObject(getSqlName("selectByCustomerId"), refCustomerId);

        CusCompanyDto cusCompanyDto = new CusCompanyDto();

        if (cusCompany != null) {

            BeanUtils.copyProperties(cusCompany, cusCompanyDto);

            List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(cusCompany.getLicense());

            cusCompanyDto.setFiles(attachments);

            String countryName = areaService.getCountryNameByCode(cusCompany.getLocationCountryCode());
            cusCompanyDto.setLocationCountryName(countryName);

            AreaDto areaDto = areaService.findByAreaId(cusCompany.getLocationCityCode(), cusCompany.getLocationCountryCode());
            if (areaDto != null) {
                cusCompanyDto.setLocationCityName(areaDto.getName());
            }
        }
        else {
            return null;
        }

        return cusCompanyDto;
    }

    @Override
    public int updateCompanyById(CusCompanyDto cusCompanyDto) {

        checkDataValid(cusCompanyDto);

        if (cusCompanyDto.getId() == null || cusCompanyDto.getId() <= 0) {

            int resId = save(cusCompanyDto);
            return resId;
        }
        List<CusCompany> cusCompanyList = dao.findForList(getSqlName("selectByCustomerId"), cusCompanyDto.getRefCustomerId(), CusCompany.class);
        if (cusCompanyList == null) {

            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND, "refcustomerid");
        }
        List<String> attachments = cusCompanyDto.getAttachFileIds();
        if (CollectionUtils.isEmpty(attachments) && !StringUtils.isEmpty(cusCompanyList.get(0).getLicense())) {

            fileGroupService.removeAllFileFromGroup(cusCompanyList.get(0).getLicense());
        }
        if (CollectionUtils.isEmpty(attachments) && StringUtils.isEmpty(cusCompanyList.get(0).getLicense())) {
            //do nothing
        }
        if (!CollectionUtils.isEmpty(attachments) && !StringUtils.isEmpty(cusCompanyList.get(0).getLicense())) {
            String fileGroupId = fileGroupService.saveFileToGroup(cusCompanyList.get(0).getLicense(), attachments,
                    "biz.customer.model", "客户" + cusCompanyList.get(0).getId() + "客户公司证件", AppDomain.OPERATION);
            cusCompanyDto.setLicense(fileGroupId);
        }
        if (!CollectionUtils.isEmpty(attachments) && StringUtils.isEmpty(cusCompanyList.get(0).getLicense())) {
            String fileGroupId = fileGroupService.createFileGroup(attachments,
                    "biz.customer.model", "客户" + cusCompanyList.get(0).getId() + "客户公司证件", AppDomain.OPERATION);
            cusCompanyDto.setLicense(fileGroupId);
        }
        BeanUtils.copyProperties(cusCompanyDto, cusCompanyList.get(0));
        dao.update(getSqlName("updateById"), cusCompanyList.get(0));

        CusCustomer cusCustomer = customerService.findCustomerById(cusCompanyDto.getRefCustomerId());
        if (checkCustomerInfoAndSetAuthStatus(cusCustomer)) {
            if (cusCustomer.getAuthStatus() == null || cusCustomer.getAuthStatus() < 1) {
                customerService.setCustomerAuthStatus(cusCompanyDto.getRefCustomerId(), 1);
            }
        }
        else {
            if (cusCustomer.getAuthStatus() == null || cusCustomer.getAuthStatus() != 0) {
                customerService.setCustomerAuthStatus(cusCompanyDto.getRefCustomerId(), 0);
            }
        }
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_CUSTOMER_COMPANY", cusCompanyList.get(0));
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UPDATE, "修改客户公司信息", dataBackup);

        return cusCompanyList.get(0).getId();

    }

    @Override
    public CusCompanyDto findByCustomerId(Integer refCustomerId) {
        CusCompany cusCompany = (CusCompany) dao.findForObject(getSqlName("selectByCustomerId"), refCustomerId);

        CusCompanyDto cusCompanyDto = new CusCompanyDto();
        if(null!=cusCompany){
            BeanUtils.copyProperties(cusCompany, cusCompanyDto);
        }else{
            return null;
        }
        return cusCompanyDto;
    }

    private void checkDataValid(CusCompanyDto cusCompanyDto) {


        if (StringUtils.isEmpty(cusCompanyDto.getFullName())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "fullname");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getLocationCountryCode())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "locationCountryCode");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getLocationCityCode())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "locationCityCode");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getResidence())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "residence");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getLegalPerson())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "legalPerson");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getTaxCode())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "taxCode");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getDepositBank())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "depositBank");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getBankAccountNo())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "bankAccountNo");
        }

        if (StringUtils.isEmpty(cusCompanyDto.getTelNo())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "telNo");
        }
    }

    private void checkCompanyExist(CusCompanyDto cusCompanyDto) {

        List<CusCompany> cusCompanyList = dao.findForList(getSqlName("selectByCustomerId"), cusCompanyDto.getRefCustomerId(), CusCompany.class);
        if (cusCompanyList != null && cusCompanyList.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EXIST, "customerId");
        }
    }

    private boolean checkCustomerInfoAndSetAuthStatus(CusCustomer cusCustomer) {
        if (cusCustomer != null) {
            if (StringUtils.isEmpty(cusCustomer.getUserName())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCustomer.getCode())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCustomer.getRefSettlementId()) || cusCustomer.getRefSettlementId() == 0) {
                return false;
            }
            if (StringUtils.isEmpty(cusCustomer.getTradingCurrency())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCustomer.getEmail())) {
                return false;
            }
        }
        else {
            return false;
        }
        return true;
    }

    @Override
    protected String getMapperNamespace() {
        return "CusCompanyMapper";
    }
}
